package com.shuosen.gmall.payment.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.shuosen.gmall.bean.OrderInfo;
import com.shuosen.gmall.bean.PaymentInfo;
import com.shuosen.gmall.bean.enums.PaymentStatus;
import com.shuosen.gmall.payment.config.AlipayConfig;
import com.shuosen.gmall.service.OrderService;
import com.shuosen.gmall.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PaymentController {

    @Reference
    PaymentService paymentService ;


    @Autowired
    AlipayClient alipayClient;

    @Reference
    OrderService  orderService  ;
//        return "redirect://payment.gmall.com/index?orderId="+orderId;
     @RequestMapping("index")
    public String index(HttpServletRequest request , Model model){
         String orderId = request.getParameter("orderId");
        OrderInfo orderInfo =  orderService.getOrderInfo(orderId);
        model.addAttribute("orderInfo",orderInfo);
        model.addAttribute("orderId",orderId);
         model.addAttribute("totalAmount",orderInfo.getTotalAmount());
         return "index" ;
     }

     @RequestMapping("alipay/submit")
     @ResponseBody
    public String alipaySubmit(HttpServletRequest request, HttpServletResponse response){
         //生成二维码
         //支付信息显示
         String orderId = request.getParameter("orderId");
         OrderInfo orderInfo = orderService.getOrderInfo(orderId);
         //保存支付信息
         PaymentInfo paymentInfo = new PaymentInfo();
         paymentInfo.setOrderId(orderId);
         paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
         paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
         paymentInfo.setSubject("测试支付");
         paymentInfo.setPaymentStatus(PaymentStatus.UNPAID);
         paymentInfo.setCreateTime(new Date());
         // 支付宝参数
         // 保存信息
         paymentService.savePaymentInfo(paymentInfo);


         AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
         alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
         alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);//在公共参数中设置回跳和通知地址

         // 声明一个Map
         Map<String,Object> bizContnetMap=new HashMap<>();
         bizContnetMap.put("out_trade_no",paymentInfo.getOutTradeNo());
         bizContnetMap.put("product_code","FAST_INSTANT_TRADE_PAY");
         bizContnetMap.put("subject",paymentInfo.getSubject());
         bizContnetMap.put("total_amount",paymentInfo.getTotalAmount());
         // 将map变成json
         String Json = JSON.toJSONString(bizContnetMap);
         alipayRequest.setBizContent(Json);

         String form="";
         try {
             form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
         } catch (AlipayApiException e) {
             e.printStackTrace();
         }
         response.setContentType("text/html;charset=UTF-8");

         //15秒执行一次，总共执行三次
         paymentService.sendDelayPaymentResult(paymentInfo.getOutTradeNo(),15,3);
         return form;
     }

    @RequestMapping(value = "/alipay/callback/return",method = RequestMethod.GET)
    public String callbackReturn(){
         //重定向到用户的订单列表
        return "redirect:"+AlipayConfig.return_order_url;
    }

    @RequestMapping(value = "/alipay/callback/notify",method = RequestMethod.POST)
    @ResponseBody
    public String paymentNotify(@RequestParam Map<String,String> paramMap, HttpServletRequest request) throws AlipayApiException {
        boolean flag = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, "utf-8",AlipayConfig.sign_type);
        if(!flag){
            return "fail";
        }
        // 判断结束
        String trade_status = paramMap.get("trade_status");
        if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)){
            // 查单据是否处理
            String out_trade_no = paramMap.get("out_trade_no");
            PaymentInfo  paymentInfo = new PaymentInfo();
            paymentInfo.setOutTradeNo(out_trade_no);
            PaymentInfo paymentInfoHas  = paymentService.getPaymentInfo(paymentInfo);
            paymentInfoHas.getPaymentStatus();
            if (paymentInfoHas.getPaymentStatus()==PaymentStatus.PAID || paymentInfoHas.getPaymentStatus()==PaymentStatus.ClOSED){
                return "fail";
            }else {
                PaymentInfo paymentInfoUpd = new PaymentInfo();
                    //设置状态
                paymentInfoUpd.setPaymentStatus(PaymentStatus.PAID);
                //设置创建时间
                paymentInfoUpd.setCallbackTime(new Date());
                //设置内容
                paymentService.updatePaymentInfo(out_trade_no,paymentInfoUpd);

                //支付模块发送通知给订单，说明支付已经完成
                paymentService.sendPaymentResult(paymentInfoHas,"success");
                return "success";
            }
        }
        return "fail";
    }

    // 发送验证
    // //http://payment.gmall.com/sendPaymentResult?orderId=101&result=success
    @RequestMapping("sendPaymentResult")
    @ResponseBody
    public String sendPaymentResult(PaymentInfo paymentInfo,String result){
        paymentService.sendPaymentResult(paymentInfo,result);
        return "sent payment result";
    }

    // payment.gmall.com/queryParamResult?orderId=97
    @RequestMapping("queryParamResult")
    @ResponseBody
    public  String queryParamResult(PaymentInfo paymentInfo){
        PaymentInfo paymentQuery = paymentService.getPaymentInfo(paymentInfo);
        boolean result = paymentService.checkPayment(paymentQuery);
        if(result){
            return "success";
        }else{
            return "false";
        }
    }


}
